#include <QApplication>
#include <QDebug>
#include <QFile> // For checking file existence
#include <QTextStream> // For reading QSS file
#include "mainwindow.h" // Include the main window header
#include "component.h"  // Include C backend header for components
#include "supplier.h"   // Include C backend header for suppliers

// --- 如果文件为空，则添加初始数据的函数 ---
void addInitialDataIfEmpty() {
    ComponentNode* compHead = nullptr;
    SupplierNode* suppHead = nullptr;
    const char* compFilename = "data/components.dat";
    const char* suppFilename = "data/suppliers.dat";
    bool compDataAdded = false;
    bool suppDataAdded = false;

    // Check components
    int compCount = load_components(compFilename, &compHead);
    if (compCount == 0) {
        qDebug() << "Component data file is empty or not found. Adding initial data...";
        // 添加一些默认组件（image_path 已初始化）
        // 格式：id, model, name, package, description, supplier_id, quantity, price, image_path
        Component c1; memset(&c1, 0, sizeof(Component));
        c1.id = 101; strncpy(c1.model, "STM32F103C8T6", COMPONENT_MODEL_LEN - 1); strncpy(c1.name, "MCU", COMPONENT_NAME_LEN - 1); strncpy(c1.package, "LQFP48", COMPONENT_PACKAGE_LEN - 1); strncpy(c1.description, "ARM Cortex-M3 Microcontroller", COMPONENT_DESCRIPTION_LEN - 1); c1.supplier_id = 1; c1.quantity = 50; c1.price = 9.0f; strncpy(c1.image_path, "", IMAGE_PATH_LEN - 1);

        Component c2; memset(&c2, 0, sizeof(Component));
        c2.id = 102; strncpy(c2.model, "NRF52832-QFAA", COMPONENT_MODEL_LEN - 1); strncpy(c2.name, "BLE SoC", COMPONENT_NAME_LEN - 1); strncpy(c2.package, "QFN48", COMPONENT_PACKAGE_LEN - 1); strncpy(c2.description, "Bluetooth Low Energy 5.2", COMPONENT_DESCRIPTION_LEN - 1); c2.supplier_id = 2; c2.quantity = 25; c2.price = 12.0f; strncpy(c2.image_path, "", IMAGE_PATH_LEN - 1);

        Component c3; memset(&c3, 0, sizeof(Component));
        c3.id = 103; strncpy(c3.model, "ESP32-WROOM-32E", COMPONENT_MODEL_LEN - 1); strncpy(c3.name, "WiFi/BT Module", COMPONENT_NAME_LEN - 1); strncpy(c3.package, "Module", COMPONENT_PACKAGE_LEN - 1); strncpy(c3.description, "Dual Core WiFi/BT", COMPONENT_DESCRIPTION_LEN - 1); c3.supplier_id = 3; c3.quantity = 100; c3.price = 10.0f; strncpy(c3.image_path, "", IMAGE_PATH_LEN - 1);

        Component c4; memset(&c4, 0, sizeof(Component));
        c4.id = 201; strncpy(c4.model, "LM358", COMPONENT_MODEL_LEN - 1); strncpy(c4.name, "OpAmp", COMPONENT_NAME_LEN - 1); strncpy(c4.package, "DIP8", COMPONENT_PACKAGE_LEN - 1); strncpy(c4.description, "Dual Operational Amplifier", COMPONENT_DESCRIPTION_LEN - 1); c4.supplier_id = 1; c4.quantity = 200; c4.price = 0.5f; strncpy(c4.image_path, "", IMAGE_PATH_LEN - 1);

        Component c5; memset(&c5, 0, sizeof(Component));
        c5.id = 301; strncpy(c5.model, "1N4148", COMPONENT_MODEL_LEN - 1); strncpy(c5.name, "Diode", COMPONENT_NAME_LEN - 1); strncpy(c5.package, "DO-35", COMPONENT_PACKAGE_LEN - 1); strncpy(c5.description, "Small Signal Diode", COMPONENT_DESCRIPTION_LEN - 1); c5.supplier_id = 4; c5.quantity = 500; c5.price = 0.05f; strncpy(c5.image_path, "", IMAGE_PATH_LEN - 1);

        Component c6; memset(&c6, 0, sizeof(Component));
        c6.id = 401; strncpy(c6.model, "BC547", COMPONENT_MODEL_LEN - 1); strncpy(c6.name, "Transistor", COMPONENT_NAME_LEN - 1); strncpy(c6.package, "TO-92", COMPONENT_PACKAGE_LEN - 1); strncpy(c6.description, "NPN BJT", COMPONENT_DESCRIPTION_LEN - 1); c6.supplier_id = 4; c6.quantity = 300; c6.price = 0.1f; strncpy(c6.image_path, "", IMAGE_PATH_LEN - 1);

        // 添加 TI 组件
        Component c7; memset(&c7, 0, sizeof(Component));
        c7.id = 501; strncpy(c7.model, "TMS320F28379D", COMPONENT_MODEL_LEN - 1); strncpy(c7.name, "C2000 Delfino MCU", COMPONENT_NAME_LEN - 1); strncpy(c7.package, "LQFP176", COMPONENT_PACKAGE_LEN - 1); strncpy(c7.description, "Core:C28x;Fmax:200MHz;Flash:1MB;", COMPONENT_DESCRIPTION_LEN - 1); c7.supplier_id = 5; c7.quantity = 10; c7.price = 25.0f; strncpy(c7.image_path, "", IMAGE_PATH_LEN - 1);

        Component c8; memset(&c8, 0, sizeof(Component));
        c8.id = 502; strncpy(c8.model, "CC2640R2F", COMPONENT_MODEL_LEN - 1); strncpy(c8.name, "SimpleLink BLE SoC", COMPONENT_NAME_LEN - 1); strncpy(c8.package, "QFN48", COMPONENT_PACKAGE_LEN - 1); strncpy(c8.description, "Core:ARM Cortex-M3;BLE:5.0;", COMPONENT_DESCRIPTION_LEN - 1); c8.supplier_id = 5; c8.quantity = 20; c8.price = 8.0f; strncpy(c8.image_path, "", IMAGE_PATH_LEN - 1);

        // 添加 Infineon 组件
        Component c9; memset(&c9, 0, sizeof(Component));
        c9.id = 601; strncpy(c9.model, "IRF540N", COMPONENT_MODEL_LEN - 1); strncpy(c9.name, "MOSFET N-CH", COMPONENT_NAME_LEN - 1); strncpy(c9.package, "TO-220", COMPONENT_PACKAGE_LEN - 1); strncpy(c9.description, "Vds:100V;Id:33A;Rds(on):44mOhm;", COMPONENT_DESCRIPTION_LEN - 1); c9.supplier_id = 6; c9.quantity = 30; c9.price = 1.5f; strncpy(c9.image_path, "", IMAGE_PATH_LEN - 1);

        Component c10; memset(&c10, 0, sizeof(Component));
        c10.id = 602; strncpy(c10.model, "TLE9879QXA40", COMPONENT_MODEL_LEN - 1); strncpy(c10.name, "Embedded Power IC", COMPONENT_NAME_LEN - 1); strncpy(c10.package, "VQFN48", COMPONENT_PACKAGE_LEN - 1); strncpy(c10.description, "Core:ARM Cortex-M3;Motor:BLDC;", COMPONENT_DESCRIPTION_LEN - 1); c10.supplier_id = 6; c10.quantity = 15; c10.price = 5.0f; strncpy(c10.image_path, "", IMAGE_PATH_LEN - 1);

        // 添加 NXP 组件
        Component c11; memset(&c11, 0, sizeof(Component));
        c11.id = 701; strncpy(c11.model, "LPC1768FBD100", COMPONENT_MODEL_LEN - 1); strncpy(c11.name, "ARM Cortex-M3 MCU", COMPONENT_NAME_LEN - 1); strncpy(c11.package, "LQFP100", COMPONENT_PACKAGE_LEN - 1); strncpy(c11.description, "Fmax:100MHz;Flash:512KB;RAM:64KB;", COMPONENT_DESCRIPTION_LEN - 1); c11.supplier_id = 7; c11.quantity = 25; c11.price = 15.0f; strncpy(c11.image_path, "", IMAGE_PATH_LEN - 1);

        Component c12; memset(&c12, 0, sizeof(Component));
        c12.id = 702; strncpy(c12.model, "PCA9685PW", COMPONENT_MODEL_LEN - 1); strncpy(c12.name, "16-ch PWM Controller", COMPONENT_NAME_LEN - 1); strncpy(c12.package, "TSSOP28", COMPONENT_PACKAGE_LEN - 1); strncpy(c12.description, "Interface:I2C;Freq:1.5kHz;", COMPONENT_DESCRIPTION_LEN - 1); c12.supplier_id = 7; c12.quantity = 40; c12.price = 2.5f; strncpy(c12.image_path, "", IMAGE_PATH_LEN - 1);

        add_component(&compHead, &c1);
        add_component(&compHead, &c2);
        add_component(&compHead, &c3);
        add_component(&compHead, &c4);
        add_component(&compHead, &c5);
        add_component(&compHead, &c6);
        add_component(&compHead, &c7);
        add_component(&compHead, &c8);
        add_component(&compHead, &c9);
        add_component(&compHead, &c10);
        add_component(&compHead, &c11);
        add_component(&compHead, &c12);

        if (save_components(compFilename, compHead) > 0) {
            qDebug() << "Initial component data saved.";
            compDataAdded = true;
        } else {
            qWarning() << "Failed to save initial component data!";
        }
    }
    // 无论是否添加了数据，都释放内存（如果文件存在，load_components 会分配内存）
    free_all_components(compHead);
    compHead = nullptr; // Reset pointer

    // Check suppliers
    int suppCount = load_suppliers(suppFilename, &suppHead);
    if (suppCount == 0) {
        qDebug() << "Supplier data file is empty or not found. Adding initial data...";
        // 添加一些默认供应商
        Supplier s1 = {1, "STMicroelectronics", "Sales Dept", "123-456-7890", "Geneva, Switzerland"};
        Supplier s2 = {2, "Nordic Semiconductor", "Support", "098-765-4321", "Trondheim, Norway"};
        Supplier s3 = {3, "Espressif Systems", "Info", "111-222-3333", "Shanghai, China"};
        Supplier s4 = {4, "ON Semiconductor", "Distributor", "444-555-6666", "Phoenix, USA"};
        // 添加新供应商
        Supplier s5 = {5, "Texas Instruments", "Support", "N/A", "Dallas, USA"};
        Supplier s6 = {6, "Infineon Technologies", "Sales", "N/A", "Neubiberg, Germany"};
        Supplier s7 = {7, "NXP Semiconductors", "Info", "N/A", "Eindhoven, Netherlands"};

        add_supplier(&suppHead, &s1);
        add_supplier(&suppHead, &s2);
        add_supplier(&suppHead, &s3);
        add_supplier(&suppHead, &s4);
        add_supplier(&suppHead, &s5);
        add_supplier(&suppHead, &s6);
        add_supplier(&suppHead, &s7);

        if (save_suppliers(suppFilename, suppHead) > 0) {
            qDebug() << "Initial supplier data saved.";
            suppDataAdded = true;
        } else {
            qWarning() << "Failed to save initial supplier data!";
        }
    }
    // 释放内存
    free_all_suppliers(suppHead);
    suppHead = nullptr; // Reset pointer

    if (compDataAdded || suppDataAdded) {
         qDebug() << "Initial data population complete.";
    }
}


int main(int argc, char *argv[])
{
    QApplication app(argc, argv); // Create the Qt Application

    // --- 测试简单文本资源加载 ---
    qDebug() << "Attempting to load test_resource.txt from resource path ':/test.txt'";
    QFile testResFile(":/test.txt");
    if (testResFile.open(QIODevice::ReadOnly | QIODevice::Text)) {
        qDebug() << "Successfully opened ':/test.txt'. Content:" << testResFile.readAll();
        testResFile.close();
    } else {
        qWarning() << "ERROR: Could not open ':/test.txt' from resources. Error:" << testResFile.errorString();
    }
    // --- 结束测试简单文本资源加载 ---

    // 加载并应用 QSS
    qDebug() << "Attempting to load QSS file from resource path ':/styles/main.qss'";
    QFile styleFile(":/styles/main.qss"); // Use the resource path/alias
    if (styleFile.open(QFile::ReadOnly | QFile::Text)) {
        qDebug() << "QSS file opened successfully:" << styleFile.fileName();
        QTextStream stream(&styleFile);
        QString styleSheetContent = stream.readAll();
        styleFile.close();
        qDebug() << "QSS content read successfully. Length:" << styleSheetContent.length();
        app.setStyleSheet(styleSheetContent);
        qDebug() << "Stylesheet set on QApplication.";
        qDebug() << "---- BEGIN APPLIED STYLESHEET ----";
        qDebug().noquote() << app.styleSheet(); // Print the actual stylesheet applied
        qDebug() << "---- END APPLIED STYLESHEET ----";
        if (app.styleSheet().isEmpty()) {
            qWarning() << "WARNING: Applied stylesheet is EMPTY!";
        }
    } else {
        qWarning() << "ERROR: Could not open QSS file:" << styleFile.fileName() << "Error:" << styleFile.errorString();
    }

    // --- 如果需要，添加初始数据（已注释掉） ---
    // addInitialDataIfEmpty();
    addInitialDataIfEmpty();
    // --- 初始数据添加结束 ---

    MainWindow mainWindow; // Create the main window instance
    mainWindow.show();     // Show the main window
    
    return app.exec();     // Start the Qt event loop
}